package com.example.com.transcribeeditpublish.popuWindow;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;

import com.bumptech.glide.Glide;
import com.example.com.transcribeeditpublish.R;
import com.example.com.transcribeeditpublish.activity.VideoEditActivity;
import com.example.com.transcribeeditpublish.utils.FileUtils;
import com.example.com.transcribeeditpublish.utils.TCPasterInfo;
import com.example.com.transcribeeditpublish.utils.paster.AnimatedPasterConfig;
import com.example.com.transcribeeditpublish.views.paster.PasterOperationView;
import com.tencent.liteav.basic.log.TXCLog;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

public class PasterPpWindow extends PopupWindow {

    private final int MSG_COPY_PASTER_FILES = 3;
    private final View menuView;
    private final VideoEditActivity context;
    private final String PASTER_FOLDER_NAME = VideoEditActivity.PASTER_FOLDER_NAME;
    private final String ANIMATED_PASTER_FOLDER_NAME = VideoEditActivity.ANIMATED_PASTER_FOLDER_NAME;
    private final String mPasterSDcardFolder = VideoEditActivity.mPasterSDcardFolder;
    private final String mAnimatedPasterSDcardFolder = VideoEditActivity.mAnimatedPasterSDcardFolder;

    private OnItemClickListener mOnItemClickListener;
    private HandlerThread mWorkHandlerThread;
    private Handler mWorkHandler;
    private boolean mIsUpdatePng = false;
    private final String PASTER_LIST_JSON_FILE_NAME = "pasterList.json";
    private List<TCPasterInfo> mPasterInfoList;
    private List<TCPasterInfo> mAnimatedPasterInfoList;
    private ViewPager viewPager;
    private String TAG = "PasterPpWindow";

    public void show(VideoEditActivity videoEditActivity) {
        this.showAtLocation(videoEditActivity.getWindow().getDecorView(), Gravity.BOTTOM, 0, 0);
    }

    public PasterPpWindow(VideoEditActivity context, OnItemClickListener listener) {
        this.context = context;
        this.mOnItemClickListener = listener;
        menuView = LayoutInflater.from(context).inflate(R.layout.popuwindow_paster, null, false);
        this.setContentView(menuView);
        //适配虚拟键
        this.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        //设置SelectPicPopupWindow弹出窗体的宽
        this.setWidth(RelativeLayout.LayoutParams.MATCH_PARENT);
        //设置SelectPicPopupWindow弹出窗体的高
        this.setHeight(RelativeLayout.LayoutParams.WRAP_CONTENT);
        //设置SelectPicPopupWindow弹出窗体可点击
        this.setFocusable(true);
        //实例化一个ColorDrawable颜色为半透明
        ColorDrawable dw = new ColorDrawable(0x00000000); //android:background="#30000000"
        //设置SelectPicPopupWindow弹出窗体的背景
        this.setBackgroundDrawable(dw);


        initTab();
        initHandler();
        mWorkHandler.sendEmptyMessage(MSG_COPY_PASTER_FILES);
    }

    private void initTab() {
        TabLayout uTab = menuView.findViewById(R.id.paster_tab);
        viewPager = menuView.findViewById(R.id.paster_vp);
        uTab.setTabMode(TabLayout.MODE_FIXED);
        uTab.setTabTextColors(menuView.getResources().getColor(R.color.D1D1D1), menuView.getResources().getColor(R.color.white));

        uTab.setSelectedTabIndicatorHeight(4);
        uTab.setSelectedTabIndicatorColor(Color.WHITE);
        ViewCompat.setElevation(uTab, 10);
        uTab.setupWithViewPager(viewPager);

    }

    private void initHandler() {
        mWorkHandlerThread = new HandlerThread("TCPasterActivity_handlerThread");
        mWorkHandlerThread.start();
        mWorkHandler = new Handler(mWorkHandlerThread.getLooper()) {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case MSG_COPY_PASTER_FILES:
                        if (mIsUpdatePng) {
                            FileUtils.deleteFile(mPasterSDcardFolder);
                            FileUtils.deleteFile(mAnimatedPasterSDcardFolder);
                        }

                        File pasterFolder = new File(mPasterSDcardFolder);
                        File animatedPasterFolder = new File(mAnimatedPasterSDcardFolder);
                        if (!pasterFolder.exists() || !animatedPasterFolder.exists()) {
                            copyPasterFilesToSdcard();
                        }
                        preparePasterInfoToShow();
                        break;
                }
            }
        };
    }

    private void preparePasterInfoToShow() {
        mPasterInfoList = getPasterInfoList(PasterOperationView.TYPE_CHILD_VIEW_PASTER, mPasterSDcardFolder, PASTER_LIST_JSON_FILE_NAME);
        mAnimatedPasterInfoList = getPasterInfoList(PasterOperationView.TYPE_CHILD_VIEW_ANIMATED_PASTER, mAnimatedPasterSDcardFolder, PASTER_LIST_JSON_FILE_NAME);

        context.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                viewPager.setAdapter(new PasterAdapter());
            }
        });
    }

    private void copyPasterFilesToSdcard() {
        File pasterFolder = new File(mPasterSDcardFolder);
        if (!pasterFolder.exists()) {
            FileUtils.copyFilesFromAssets(context, PASTER_FOLDER_NAME, mPasterSDcardFolder);
        }
        File animatedFolder = new File(mAnimatedPasterSDcardFolder);
        if (!animatedFolder.exists()) {
            FileUtils.copyFilesFromAssets(context, ANIMATED_PASTER_FOLDER_NAME, mAnimatedPasterSDcardFolder);
        }
    }

    private List<TCPasterInfo> getPasterInfoList(int pasterType, String fileFolder, String fileName) {
        String filePath = fileFolder + fileName;
        List<TCPasterInfo> pasterInfoList = new ArrayList<TCPasterInfo>();
        try {
            String jsonString = FileUtils.getJsonFromFile(filePath);
            if (TextUtils.isEmpty(jsonString)) {
                TXCLog.e("getPasterInfoList", "getPasterInfoList, jsonString is empty");
                return pasterInfoList;
            }
            JSONObject pasterJson = new JSONObject(jsonString);
            JSONArray pasterInfoJsonArray = pasterJson.getJSONArray("pasterList");
            for (int i = 0; i < pasterInfoJsonArray.length(); i++) {
                JSONObject pasterInfoJsonObject = pasterInfoJsonArray.getJSONObject(i);
                TCPasterInfo tcPasterInfo = new TCPasterInfo();

                tcPasterInfo.setName(pasterInfoJsonObject.getString("name"));
                tcPasterInfo.setIconPath(fileFolder + pasterInfoJsonObject.getString("icon"));
                tcPasterInfo.setPasterType(pasterType);

                pasterInfoList.add(tcPasterInfo);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return pasterInfoList;
    }


    private class PasterAdapter extends PagerAdapter {

        @Override
        public int getCount() {
            return 2;
        }

        @Override
        public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
            return view == object;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            RecyclerView recyclerView = new RecyclerView(context);
            recyclerView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
            recyclerView.setLayoutManager(new GridLayoutManager(context, 3));
            recyclerView.setAdapter(new PasterRVAdapter(position == 0 ? mAnimatedPasterInfoList : mPasterInfoList));
            container.addView(recyclerView);
            //最后要返回的是控件本身
            return recyclerView;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }

        @Nullable
        @Override
        public CharSequence getPageTitle(int position) {
            return position == 0 ? "动态贴纸" : "静态贴纸";
        }
    }

    private class PasterRVAdapter extends RecyclerView.Adapter<PasterViewHolder> implements View.OnClickListener {

        private final List<TCPasterInfo> mPasterInfoList;
        private WeakReference<RecyclerView> mRecyclerView;

        public PasterRVAdapter(List<TCPasterInfo> pasterInfoList) {
            if (pasterInfoList == null) {
                mPasterInfoList = new ArrayList<TCPasterInfo>();
            } else {
                mPasterInfoList = pasterInfoList;
            }
        }


        @Override
        public PasterViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            if (mRecyclerView == null) {
                mRecyclerView = new WeakReference<RecyclerView>((RecyclerView) parent);
            }
            return new PasterViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_paster_view, null));
        }

        @Override
        public void onBindViewHolder(PasterViewHolder holder, int position) {
            holder.itemView.setOnClickListener(this);
            Glide.with(holder.itemView.getContext()).load(mPasterInfoList.get(position).getIconPath()).into(holder.ivPaster);
        }

        @Override
        public void onClick(View view) {
            if (mOnItemClickListener == null) {
                return;
            }
            RecyclerView recyclerView = mRecyclerView.get();
            if (recyclerView != null) {
                int position = recyclerView.getChildAdapterPosition(view);
                setBipmapAndPath(mPasterInfoList.get(position));
            }
        }

        @Override
        public int getItemCount() {
            return mPasterInfoList.size();
        }

    }

    private class PasterViewHolder extends RecyclerView.ViewHolder {

        private final ImageView ivPaster;

        public PasterViewHolder(View inflate) {
            super(inflate);
            ivPaster = (ImageView) itemView.findViewById(R.id.iv_paster);
        }
    }

    public interface OnItemClickListener {

        void onItemClick(TCPasterInfo tcPasterInfo, String pasterPath, Bitmap bitmap);
    }

    public void setBipmapAndPath(TCPasterInfo tcPasterInfo) {
        String pasterPath = null;
        Bitmap bitmap = null;
        int pasterType = tcPasterInfo.getPasterType();
        if (pasterType == PasterOperationView.TYPE_CHILD_VIEW_ANIMATED_PASTER) {
            AnimatedPasterConfig animatedPasterConfig = getAnimatedPasterParamFromPath(mAnimatedPasterSDcardFolder + tcPasterInfo.getName() + File.separator);
            if (animatedPasterConfig == null) {
                TXCLog.e(TAG, "onItemClick, animatedPasterConfig is null");
                return;
            }
            int keyFrameIndex = animatedPasterConfig.keyframe;
            String keyFrameName = animatedPasterConfig.frameArray.get(keyFrameIndex - 1).pictureName;
            pasterPath = mAnimatedPasterSDcardFolder + tcPasterInfo.getName() + File.separator + keyFrameName + ".png";
            bitmap = BitmapFactory.decodeFile(pasterPath);
        } else if (pasterType == PasterOperationView.TYPE_CHILD_VIEW_PASTER) {
            pasterPath = mPasterSDcardFolder + tcPasterInfo.getName() + File.separator + tcPasterInfo.getName() + ".png";
            bitmap = BitmapFactory.decodeFile(pasterPath);
        }

        mOnItemClickListener.onItemClick(tcPasterInfo, pasterPath, bitmap);
    }

    private AnimatedPasterConfig getAnimatedPasterParamFromPath(String pathFolder) {
        AnimatedPasterConfig animatedPasterConfig = null;
        String configPath = pathFolder + AnimatedPasterConfig.FILE_NAME;

        String configJsonStr = FileUtils.getJsonFromFile(configPath);

        if (TextUtils.isEmpty(configJsonStr)) {
            TXCLog.e(TAG, "getTXAnimatedPasterParamFromPath, configJsonStr is empty");
            return animatedPasterConfig;
        }

        JSONObject jsonObjectConfig = null;
        try {
            jsonObjectConfig = new JSONObject(configJsonStr);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        if (jsonObjectConfig == null) {
            TXCLog.e(TAG, "getTXAnimatedPasterParamFromPath, jsonObjectConfig is null");
            return animatedPasterConfig;
        }

        animatedPasterConfig = new AnimatedPasterConfig();
        try {
            animatedPasterConfig.name = jsonObjectConfig.getString(AnimatedPasterConfig.CONFIG_NAME);
            animatedPasterConfig.count = jsonObjectConfig.getInt(AnimatedPasterConfig.CONFIG_COUNT);
            animatedPasterConfig.period = jsonObjectConfig.getInt(AnimatedPasterConfig.CONFIG_PERIOD);
            animatedPasterConfig.width = jsonObjectConfig.getInt(AnimatedPasterConfig.CONFIG_WIDTH);
            animatedPasterConfig.height = jsonObjectConfig.getInt(AnimatedPasterConfig.CONFIG_HEIGHT);
            animatedPasterConfig.keyframe = jsonObjectConfig.getInt(AnimatedPasterConfig.CONFIG_KEYFRAME);
            JSONArray frameJsonArray = jsonObjectConfig.getJSONArray(AnimatedPasterConfig.CONFIG_KEYFRAME_ARRAY);
            for (int i = 0; i < animatedPasterConfig.count; i++) {
                JSONObject frameNameObject = frameJsonArray.getJSONObject(i);
                AnimatedPasterConfig.PasterPicture pasterPicture = new AnimatedPasterConfig.PasterPicture();
                pasterPicture.pictureName = frameNameObject.getString(AnimatedPasterConfig.PasterPicture.PICTURE_NAME);
                animatedPasterConfig.frameArray.add(pasterPicture);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return animatedPasterConfig;
    }
}
